package tgc.rj.zz.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import tgc.rj.zz.custom.DatagridFormUtils;
import tgc.rj.zz.custom.LogUtils;
import tgc.rj.zz.entity.Bj;
import tgc.rj.zz.entity.Books;
import tgc.rj.zz.entity.Log;
import tgc.rj.zz.entity.Record;
import tgc.rj.zz.entity.SysUser;
import tgc.rj.zz.repository.SysUserRepository;
import tgc.rj.zz.security.UserUtils;
import tgc.rj.zz.service.BjService;
import tgc.rj.zz.service.BooksService;
import tgc.rj.zz.service.LogService;
import tgc.rj.zz.service.RecordService;

@Controller
public class LoginController {

	@Autowired
	private BooksService service;
	@Autowired
	private  UserUtils userUtils;
	@Autowired
	private LogUtils logUtils;
	@Autowired
	private LogService logDAO;
	@Autowired
	private SysUserRepository sysDAO;
	@Autowired
	private BjService bjDAO;
	@Autowired
	private RecordService recordDAO;
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String login(ModelMap map,HttpSession session) {
		List<Books> books = service.findAll();
		List<Bj> bjs = bjDAO.findAll();
		map.put("books", books);
		map.put("bjs", bjs);
		return "login";
		
	}
	@RequestMapping(value="/main")
	public String main(ModelMap map,HttpServletRequest request,HttpSession session){
		SysUser user2 = userUtils.getUser();
		if(user2.getIdentity()==0){
			SysUser user = userUtils.getUser();
			logUtils.log(user.getUsername(),user.getName(),"登陆");
			System.out.println("管理员登陆了");
			return "main"; 
		}else {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = df.format(new Date());
			Boolean f = true;
			Date dqDate;
			try {
				dqDate = df.parse(date);
				List<Record> reader = recordDAO.findByReader(user2.getId());
				for (Record r : reader) {
					Date endDate = df.parse(r.getEndDate());
					if(endDate.before(dqDate)&&r.getAccredit().equals("已借出")){
						f = false;
						break;
					}
				}
			} catch (ParseException e) {
				e.printStackTrace();
			}
			if(f){
				session.removeAttribute("time");
				List<Books> books = service.findAll();
				map.put("books", books);
				SysUser user = userUtils.getUser();
				logUtils.log(user.getUsername(),user.getName(),"登陆");
				System.out.println("用户登陆了");
				return "main";
			}else{
				//request.setAttribute("time", "您违约了还书日期，账号已被封，请带上书本和相关证件立即联系管理员解封，否则后果自负！");
				//HashMap<String, String> m = new HashMap<>();
				//m.put("time", "您违约了还书日期，账号已被封，请带上书本和相关证件立即联系管理员解封，否则后果自负！");
				session.setAttribute("time", "您违约了还书日期，账号已被封，请带上书本和相关证件立即联系管理员解封，否则后果自负！");
				return "redirect:login";
			}
		}
	}
	
	/*
	 * 退出日志
	 */
	@RequestMapping("/logoutc")
	public String logout() {
		SysUser user = userUtils.getUser();
		logUtils.log(user.getUsername(),user.getName(),"退出");
		return "redirect:logout";
	}
	
	/*
	 * 用户主页加载图书
	 */
	@RequestMapping(value="/download")
	@ResponseBody
	public Object download(Integer id, HttpServletRequest request, HttpServletResponse response) {
		service.download(id, request, response);
		return null;
	}
	
	/*
	 * 用户操作日志
	 */
	@RequestMapping("/log")
	public String log() {
		return "log/log";
	}
	
	@RequestMapping("/listLog")
	@ResponseBody
	public Object log(DatagridFormUtils custom) {
		Pageable pageable = custom.buildPageable();
		Page<Log> page = null;
		if (custom.getId()==null) {
			page = logDAO.findAll(pageable);
		}else{
			page = logDAO.findAll(custom.logBuildSpes(), pageable);
		}
		HashMap<String, Object> result = DatagridFormUtils.getPageResult(page);
		return result;
	}
	/*
	 * 多级用户修改密码页面
	 */
	@RequestMapping("/changePwd")
	 public String changePwd() {
		return "pwd/changePwd";
		 
	 }
	/*
	 * 判断原密码
	 */
	@RequestMapping("/password")
	@ResponseBody
	public Boolean pwd(String password) {
		SysUser user = userUtils.getUser();
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		boolean pwd = encoder.matches(password, user.getPassword());
		return pwd;
		
	}
	/*
	 * 修改密码
	 */
	@RequestMapping("/change")
	public String change(String newPwd) {
		SysUser user = userUtils.getUser();
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		user.setPassword(encoder.encode(newPwd));
		sysDAO.save(user);
		return "redirect:logout";
		
	}
}

